import { defineStore } from 'pinia'
import { store } from '@/store'
import { userType } from './types'
import { useCommonStoreHook } from '@/store/modules/common'
import { _userPlaylist, _like, _likelist } from '@/service/song'

const commonStore = useCommonStoreHook()

export const useUserStore = defineStore({
  id: 'music-user',
  state: (): userType => ({
    userPlaylist: [],
    like: {},
    likeIds: [],
    subscribeList: []
  }),
  getters: {},
  actions: {
    async initUserPlaylist() {
      if (!commonStore.profile.userId) return
      this.userPlaylist = []
      const { playlist } = await _userPlaylist({
        uid: commonStore.profile.userId
      })
      this.subscribeList = playlist.filter((ele) => {
        if (!ele.subscribed) {
          if (ele.specialType !== 5) {
            this.userPlaylist.push(ele)
          } else {
            this.like = ele
            this.setLike()
          }
        }
        return ele.subscribed
      })
    },
    setLike() {
      _likelist({ uid: commonStore.profile.userId }).then((res) => {
        this.likeIds = res.ids
      })
    },
    likeChange(song) {
      const params = {
        id: song.id,
        like: !this.likeIds.includes(song.id)
      }
      _like(params).then((res) => {
        this.setLike()
      })
    }
  }
})

export function useUserStoreHook() {
  return useUserStore(store)
}
